package cn.felord;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * The interface Broker.
 *
 * @author felord.cn
 * @since 10 :28
 */
public class Broker {

    private final ConcurrentHashMap<String, Set<Subscriber>> subscribers = new ConcurrentHashMap<>();

    private Broker() {
    }

    private static class Instance {
        private static final Broker INSTANCE = new Broker();
    }

    public static Broker getInstance() {
        return Instance.INSTANCE;
    }

    public boolean addSub(String topic, Subscriber subscriber) {

        if (subscribers.get(topic) == null) {
            Set<Subscriber> objects = new HashSet<>();
            objects.add(subscriber);
            subscribers.put(topic, objects);
        }
        return subscribers.get(topic).add(subscriber);
    }

    public boolean removeSub(String topic, Subscriber subscriber) {
        if (subscribers.get(topic) == null) {
            return true;
        }
        return subscribers.get(topic).remove(subscriber);
    }


    public void broadcasting(String topic, String msg) {
        subscribers.get(topic).forEach(subscriber -> subscriber.onEvent(msg));
    }


}
